<template>
  <div>
    <dialog-with-save
      :visible.sync="visible"
      :title="title"
      :width="width"
      @save="save"
    >
      <el-form
        ref="editForm"
        label-position="top"
        :model="model"
        :rules="rules"
      >
        <el-form-item
          :label="L('CurrentPassword')"
          prop="currentPassword"
        >
          <el-input
            v-model="model.currentPassword"
            type="password"
            :maxlength="32"
          />
        </el-form-item>
        <el-form-item
          :label="L('NewPassword')"
          prop="newPassword"
        >
          <el-input
            v-model="model.newPassword"
            type="password"
            :maxlength="32"
          />
        </el-form-item>
        <el-form-item
          :label="L('NewPasswordRepeat')"
          prop="newPasswordRepeat"
        >
          <el-input
            v-model="model.newPasswordRepeat"
            type="password"
            :maxlength="32"
          />
        </el-form-item>
      </el-form>
    </dialog-with-save>
  </div>
  <!-- 调用 this.$refs.CreateOrEditOu.open() -->
</template>

<script>
import dialogWithSave from '@/components/DialogWithSave' // waves directive
import { mapActions } from 'vuex'
export default {
  name: 'ChangePassword',
  components: { dialogWithSave },
  data() {
    const validatePassCheck = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.L('EnterPasswordAganin')))
      } else if (value !== this.model.newPassword) {
        callback(new Error(this.L('TwoPasswordNotMatch')))
      } else {
        callback()
      }
    }

    return {
      title: this.L('ChangePassword'),
      visible: false,
      width: '500px',

      model: {
        currentPassword: '',
        newPassword: '',
        newPasswordRepeat: ''
      },
      rules: {
        currentPassword: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('CurrentPassword')), trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: this.L('FieldIsRequired', undefined, this.L('NewPassword')), trigger: 'blur' }
        ],
        newPasswordRepeat: { validator: validatePassCheck, trigger: 'blur' }
      }
    }
  },
  methods: {
    ...mapActions('profile', ['changePassword']),
    open() {
      this.visible = true
      this.$nextTick(() => {
        this.model = {}
        this.$refs.editForm.clearValidate()
      })
    },
    save(cb) {
      cb(() => {
        return new Promise((resolve, reject) => {
          this.$refs.editForm.validate(async val => {
            if (val) {
              await this.changePassword({ data: this.model }).catch(err => { reject(err) })
              resolve(val)
            } else {
              reject(val)
            }
          })
        })
      })
    }
  }
}
</script>

